package com.xhc.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhc.entity.Stock;
import com.xhc.lock.DisLockClient;
import com.xhc.lock.MyRedisLock;
import com.xhc.lock.MyZookeeperLock;
import com.xhc.mapper.StockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class StockService {

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private DisLockClient lockClient;

    public void deduct(){
        // 加锁
//        MyRedisLock rlock = lockClient.buildRedisLock("lock");
//        rlock.lock();
        MyZookeeperLock zlock = lockClient.buildZookeeperLock("lock");
        zlock.lock();

        // 业务操作
        Stock stock = this.stockMapper.selectOne(new QueryWrapper<Stock>().eq("code", "1001"));
        if (stock != null && stock.getCount()>0){
            stock.setCount(stock.getCount() - 1);
            this.stockMapper.updateById(stock);
        }

//        this.testReentry();

        // 解锁
//        rlock.unlock();
        zlock.unlock();
    }

    /**
     * 测试锁的可重入性
     */
    private void testReentry(){
        // 加锁
//        MyRedisLock rlock = lockClient.buildRedisLock("lock");
//        rlock.lock();
        MyZookeeperLock zlock = lockClient.buildZookeeperLock("lock");
        zlock.lock();

        System.out.println("测试可重入性");

        // 解锁
//        rlock.unlock();
        zlock.unlock();
    }
}
